package com.zhanglijie.base.volatileLearn;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/5/15 0015 18:35
 * 演示volatile内存可见性
 */
public class ConsumerProducer {
    static int i = 0;

    public static void main(String[] args) {
        new Thread(()->{
            while(true){
               // System.out.println(); sync
              //  synchronized (new Object()){}; sync
                try {
                    Thread.sleep(1); //c++层面有互斥锁
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(i==1) {
                    System.out.println("值改变了退出循环");
                    break;
                }
            }

        },"thread-0").start();

        new Thread(()->{
            try {
                //Thread.sleep(2000); 也可以使用自旋两秒
                mysleep(2000000000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            i=1;
        },"thread-1").start();
    }

    /**
     * @param timeout 单位是纳秒
     */
    private static void mysleep(int timeout) {
        long start = System.nanoTime();
        long end;
        do{
            end = System.nanoTime();
        }while(end-start<=timeout);
    }
}
